<?php

namespace App\Exports;

use App\Models\SerialNumber\SerialNumber;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class SerialNumberExport extends DefaultValueBinder implements FromArray,WithCustomValueBinder
{

    private $conditions;

    public function __construct($conditions) {
        $this->conditions = $conditions;
    }

    public function array():array {
        $data = [
            ['ID','序列号','创建时间','类型','绑定人','手机','身份证号','激活时间','状态','备注'],
        ];

        $records = (new SerialNumber())->getLst($this->conditions)
            ->with(['getDriverInfo:id,user_id,name,id_card','getUserInfo:id,active_time,phone'])->get();

        foreach ($records as $record) {
            $temp = [
                $record->id,
                $record->serial_number,
                $record->created_at,
                $record->type,
                $record->getDriverInfo->name??'',
                $record->getUserInfo->phone??'',
                $record->getDriverInfo->id_card??'',
                $record->get_user_info->active_time??'',
                $record->status==1?'已送出':'未送出',
                $record->beizhu,
            ];
            $data[] = $temp;
        }
        return $data;
    }

    public function bindValue(Cell $cell, $value) {
        if (strlen($value) > 10) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }
}
